import request, {Method} from '../utils/request'
import Cache, {Keys} from '@/utils/cache.js';
import * as API_Connect from '@/api/connect.js';

/**
 * openid相关操作
 * 妙贤 2020-09-30
 */



/**
 * 生成授权获取openid的跳转链接
 */
export function createRedirectUri() {
    return new Promise(function(resolve, reject) {
        let redirectUri = window.location.href;
        redirectUri = encodeURIComponent(redirectUri)
        console.log("redirectUri--" + redirectUri)
        API_Connect.wxH5GetLoginUrl(redirectUri).then(res => {
            //传回后端跳转的url
            resolve(res)
        }).catch(e=>{
            reject(e)
        })
    })
}

/**
 * 获取openid
 */
export function fetchWeiXinH5OpenId(code) {

    return new Promise(function(resolve, reject) {
        //调用api获取微信openid
        fetchH5OpenId(code).then(openid => {
            if(openid==''){
                openid='error'
            }
            //将openid存入cache
            Cache.setItem(Keys.wxopenid, openid)
            resolve(openid)
        }).catch(e=>{
            reject(e)
        })
    })

}

/**
 * 通过uniapp提供的api
 * 获取微信小程序 openid
 */
export async function fetchWeixinMiniOpenId(){
    const loginRes = await wxMiniLogin();
    // console.log(loginRes)
    return new Promise(function(resolve, reject) {
        const code = loginRes.code
        fetchMiniOpenId(code).then(openid=>{
            if(openid==''){
                openid='error'
            }
            Cache.setItem(Keys.wxopenid, openid)
            resolve(openid)
        }).catch(e=>{
            reject(e)
        })
   })
}

/**
 * 小程序登录，返回code
 */
function wxMiniLogin(){
    return new Promise(function(resolve, reject) {
         uni.login({
              provider: 'weixin',
              success: function (loginRes) {
                // console.log(loginRes)
                resolve(loginRes)
              }
        })
    })
}



/**
 * 通过api获取微信h5的用户openid
 * @param {Object} code
 */
function fetchH5OpenId(code) {
    return request.ajax({
        url: '/wechat/h5/openid',
        method: Method.GET,
        params: {
            code
        }
    })
}


/**
 * 通过api获取微信小程序的用户openid
 * @param {Object} code
 */
async function fetchMiniOpenId(code) {
    return request.ajax({
        url: '/wechat/mini/openid',
        method: Method.GET,
        params: {
            code
        }
    })
}



